<?php
if (!$_SESSION['sid']) {
    exit('Permission Denied!');
}
//header('Content-type: image/jpg');
//define('DEFAULT_WECHAT_APPID', 'wxd72be21f7455640d');
//define('DEFAULT_WECHAT_APPID', 'wx2d67b2919b8f0fa2');
//define('DEFAULT_WECHAT_APPID', 'wx5f3f2fba331ad1c6');
include '/var/www/html/wx/wechat/open_wechat.php';
$dbConf = include '/var/www/html/new/d/module/common/db.conf.php';
include '/var/www/html/new/d/module/common/Db.class.php';
include '/var/www/html/new/d/class/Api.class.php';
\PFT\Db::Conf($dbConf['remote_1']);
//TODO::检测是否有绑定过微信公众号
$sql = "SELECT appid FROM pft_wx_open WHERE fid=? LIMIT 1";
$stmt = \PFT\Db::Connect()->prepare($sql);
$stmt->execute(array($_SESSION['sid']));
$appid = $stmt->fetchColumn();
if (!$appid) {
    Api::Response('还没有绑定过微信服务号', Api::badRequestCode, 'alert');
}
define('WECHAT_APPID', $appid);
if (!$_POST['fid'] ||!is_numeric($_POST['fid'])) {
    Api::Response('请选择分销商，谢谢', Api::badRequestCode, 'alert');
}
//TODO::保存微信分店信息，得到分店ID
$sql = "SELECT id FROM pft_wxshops WHERE aid=? AND fid=? LIMIT 1";
$stmt = \PFT\Db::Connect()->prepare($sql);
$stmt->execute(array($_SESSION['sid'], intval($_POST['fid'])));
$shop_id = $stmt->fetchColumn();
if (!$shop_id) {
    $sql_insert = "INSERT INTO pft_wxshops (aid,fid,name) VALUES(?,?,?)";
    $stmt = \PFT\Db::Connect()->prepare($sql_insert);
    try {
        $stmt->execute(array(
            $_SESSION ['sid'],
            $_POST['fid'],
            trim($_POST['name']))
        );
    } catch(PDOException $e) {
        echo $e->getMessage();
        exit;
    }
    $shop_id = \PFT\Db::Connect()->lastInsertId();
}
//TODO::根据分店ID向微信服务器发送请求生成带参数的二维码
//第三个参数微信分店ID
$res = \LaneWeChat\Core\Popularize::createTicket(2,0,$shop_id);
if ($res['errcode']) {
    if ($res['errcode']==48001) $msg = "您的微信公众号api功能未授权，请确认公众号已获得该接口，可以在公众平台官网-开发者中心页中查看接口权限";
    else {$msg = "错误代码：{$res['errcode']}";}
    \PFT\Db::Connect()->exec("DELETE FROM pft_wxshops WHERE id=$shop_id LIMIT 1");
    echo <<<SCRIPT
<script>alert('添加失败,{$msg}');</script>
SCRIPT;
    exit;
}
$qr_ret = \LaneWeChat\Core\Popularize::getQrcode($res['ticket']);
//var_dump($qr_ret);
//exit;
//TODO::保存二维码咯
$dir  = "/var/www/html/wx/";
$name = "public/wx_shops_qr/{$_SESSION ['sid']}_{$_POST['fid']}_{$shop_id}.jpg";
$local_file = fopen($dir . $name, 'w');
if (false !== $local_file) {
    if (false !== fwrite($local_file, $qr_ret)) {
        fclose($local_file);
    }
}
//TODO::更新数据库图片路径,有点问题
$url_name = 'http://wx.12301.cc/' . $name;
$sql_update = "UPDATE pft_wxshops SET qr_path='$url_name' WHERE id=$shop_id LIMIT 1";
$stmt = \PFT\Db::Connect()->prepare($sql_update);
$ret  = $stmt->execute();
\PFT\Db::Close();
if ($ret) {
    if ($_POST['show_qr']) {
        echo "<img src='$url_name'/>";
    } else {
        echo <<<SCRIPT
<script>alert('添加成功！');parent.location.reload();</script>
SCRIPT;
        Api::Response('ok', Api::okCode);
    }


}
//echo $qr_ret;


